package me.may.money.service;

import java.util.LinkedHashMap;

import me.may.money.dao.CacheDao;
import me.may.money.dao.MoneyDao;

/**
 * 交子应用层实现类
 * 
 * @author May_Speed
 */
public class MoneyServiceImpl implements MoneyService {

	@Override
	public double getPlayerMoney(String name) {
		if (name == null || name.equalsIgnoreCase("")) {
			return 0;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
			return 0;
		}
		if (CacheDao.hasPlayerDataInCache(name)) {
			return Double.valueOf(CacheDao.getPlayerCacheData(name)).doubleValue();
		} else {
			return Double.valueOf(MoneyDao.getPlayerMoney(name)).doubleValue();
		}
	}

	@Override
	public void addPlayerMoney(String name, double amount) {
		if (name == null || name.equalsIgnoreCase("")) {
			return;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
			return;
		}
		MoneyDao.addPlayerMoney(name, String.valueOf(amount));
	}

	@Override
	public void takePlayerMoney(String name, double amount) {
		if (name == null || name.equalsIgnoreCase("")) {
			return;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
			return;
		}
		MoneyDao.takePlayerMoney(name, String.valueOf(amount));
	}

	@Override
	public void setPlayerMoney(String name, double amount) {
		if (name == null || name.equalsIgnoreCase("")) {
			return;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
			return;
		}
		MoneyDao.setPlayerMoney(name, String.valueOf(amount));
	}

	@Override
	public void initialPlayerAccount(String name) {
		if (name == null || name.equalsIgnoreCase("")) {
			return;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
		}
	}
	
	@Override
	public boolean hasEnoughMoney(String name, double amount) {
		if (name == null || name.equalsIgnoreCase("")) {
			return false;
		}
		if (!hasMoneyAccount(name)) {
			MoneyDao.initialPlayerData(name);
			return false;
		}
		double money = 0.0D;
		if (CacheDao.hasPlayerDataInCache(name)) {
			money = Double.valueOf(CacheDao.getPlayerCacheData(name)).doubleValue();
		} else {
			money = Double.valueOf(MoneyDao.getPlayerMoney(name)).doubleValue();
		}
		return money >= amount;
	}

	@Override
	public boolean hasMoneyAccount(String name) {
		if (name == null || name.equalsIgnoreCase("")) {
			return false;
		}
		if (CacheDao.hasPlayerDataInCache(name)) {
			return true;
		}
		if (MoneyDao.playerHasData(name)) {
			return true;
		}
		return false;
	}

	@Override
	public LinkedHashMap<String, Double> getTop(int limit) {
		return MoneyDao.getTop(limit);
	}
}
